//
//  UIImage+Extension.swift
//  AoNongOA
//
//  Created by zwb on 16/8/8.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit
import ImageIO

extension UIImageView {

    public func loadGif(name: String) {
        DispatchQueue.global().async {
            let image = UIImage.gif(name: name)
            DispatchQueue.main.async {
                self.image = image
            }
        }
    }

    @available(iOS 9.0, *)
    public func loadGif(asset: String) {
        DispatchQueue.global().async {
            let image = UIImage.gif(asset: asset)
            DispatchQueue.main.async {
                self.image = image
            }
        }
    }

}

extension UIImage {

    public class func gif(data: Data) -> UIImage? {
        // Create source from data
        guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {
            print("SwiftGif: Source for the image does not exist")
            return nil
        }

        return UIImage.animatedImageWithSource(source)
    }

    public class func gif(url: String) -> UIImage? {
        // Validate URL
        guard let bundleURL = URL(string: url) else {
            print("SwiftGif: This image named \"\(url)\" does not exist")
            return nil
        }

        // Validate data
        guard let imageData = try? Data(contentsOf: bundleURL) else {
            print("SwiftGif: Cannot turn image named \"\(url)\" into NSData")
            return nil
        }

        return gif(data: imageData)
    }

    public class func gif(name: String) -> UIImage? {
        // Check for existance of gif
        guard let bundleURL = Bundle.main
          .url(forResource: name, withExtension: "gif") else {
            print("SwiftGif: This image named \"\(name)\" does not exist")
            return nil
        }

        // Validate data
        guard let imageData = try? Data(contentsOf: bundleURL) else {
            print("SwiftGif: Cannot turn image named \"\(name)\" into NSData")
            return nil
        }

        return gif(data: imageData)
    }

    @available(iOS 9.0, *)
    public class func gif(asset: String) -> UIImage? {
        // Create source from assets catalog
        guard let dataAsset = NSDataAsset(name: asset) else {
            print("SwiftGif: Cannot turn image named \"\(asset)\" into NSDataAsset")
            return nil
        }

        return gif(data: dataAsset.data)
    }

    internal class func delayForImageAtIndex(_ index: Int, source: CGImageSource!) -> Double {
        var delay = 0.1

        // Get dictionaries
        let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
        let gifPropertiesPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 0)
        defer {
            gifPropertiesPointer.deallocate()
        }
        if CFDictionaryGetValueIfPresent(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque(), gifPropertiesPointer) == false {
            return delay
        }

        let gifProperties:CFDictionary = unsafeBitCast(gifPropertiesPointer.pointee, to: CFDictionary.self)

        // Get delay time
        var delayObject: AnyObject = unsafeBitCast(
            CFDictionaryGetValue(gifProperties,
                Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()),
            to: AnyObject.self)
        if delayObject.doubleValue == 0 {
            delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties,
                Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self)
        }

        if let delayObject = delayObject as? Double, delayObject > 0 {
            delay = delayObject
        } else {
            delay = 0.1 // Make sure they're not too fast
        }

        return delay
    }

    internal class func gcdForPair(_ a: Int?, _ b: Int?) -> Int {
        var a = a
        var b = b
        // Check if one of them is nil
        if b == nil || a == nil {
            if b != nil {
                return b!
            } else if a != nil {
                return a!
            } else {
                return 0
            }
        }

        // Swap for modulo
        if a! < b! {
            let c = a
            a = b
            b = c
        }

        // Get greatest common divisor
        var rest: Int
        while true {
            rest = a! % b!

            if rest == 0 {
                return b! // Found it
            } else {
                a = b
                b = rest
            }
        }
    }

    internal class func gcdForArray(_ array: Array<Int>) -> Int {
        if array.isEmpty {
            return 1
        }

        var gcd = array[0]

        for val in array {
            gcd = UIImage.gcdForPair(val, gcd)
        }

        return gcd
    }

    internal class func animatedImageWithSource(_ source: CGImageSource) -> UIImage? {
        let count = CGImageSourceGetCount(source)
        var images = [CGImage]()
        var delays = [Int]()

        // Fill arrays
        for i in 0..<count {
            // Add image
            if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
                images.append(image)
            }

            // At it's delay in cs
            let delaySeconds = UIImage.delayForImageAtIndex(Int(i),
                source: source)
            delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms
        }

        // Calculate full duration
        let duration: Int = {
            var sum = 0

            for val: Int in delays {
                sum += val
            }

            return sum
            }()

        // Get frames
        let gcd = gcdForArray(delays)
        var frames = [UIImage]()

        var frame: UIImage
        var frameCount: Int
        for i in 0..<count {
            frame = UIImage(cgImage: images[Int(i)])
            frameCount = Int(delays[Int(i)] / gcd)

            for _ in 0..<frameCount {
                frames.append(frame)
            }
        }

        // Heyhey
        let animation = UIImage.animatedImage(with: frames,
            duration: Double(duration) / 1000.0)

        return animation
    }

}
extension UIImage {
    
    
    //将图片裁剪成指定比例（多余部分自动删除）
    func crop(ratio: CGFloat) -> UIImage {
        //计算最终尺寸
        var newSize:CGSize!
        if size.width/size.height > ratio {
            newSize = CGSize(width: size.height * ratio, height: size.height)
        }else{
            newSize = CGSize(width: size.width, height: size.width / ratio)
        }
        
        ////图片绘制区域
        var rect = CGRect.zero
        rect.size.width  = size.width
        rect.size.height = size.height
        rect.origin.x    = (newSize.width - size.width ) / 2.0
        rect.origin.y    = (newSize.height - size.height ) / 2.0
        
        
        //绘制并获取最终图片
        UIGraphicsBeginImageContextWithOptions(newSize, false, 2)  // 1 会模糊  2 和 3 不会模糊，什么区别待验证
        draw(in: rect)
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return scaledImage!
    }
    
    
    
    //将图片裁剪成指定比例（多余部分自动删除）
    func crop(rect: CGRect) -> UIImage? {
        
        
        print(self.size)
        
        var recssss = rect
        //        recssss.origin.x    =  self.size.width * 0.2
        //        recssss.origin.y    = self.size.width * 0.2
        //        recssss.size.width = self.size.width * 0.5
        //        recssss.size.height = self.size.height * 0.5
        //绘制并获取最终图片
        ////图片绘制区域
        var newrect = CGRect.zero
        newrect.size.width  = size.width
        newrect.size.height = size.height
        newrect.origin.x    = -recssss.origin.x
        newrect.origin.y    = -recssss.origin.y
        
        UIGraphicsBeginImageContextWithOptions(recssss.size, false, 0)
        draw(in: newrect)
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return scaledImage
    }
    
    
    
    
    // 裁剪一下，然后base64
    public func toBase64() -> String {
        let data = resetImgSize(sourceImage: self, maxImageLenght: 900, maxSizeKB: 200)
        let encodedImageStr = data.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength64Characters)
        return encodedImageStr
    }
    
    
    
    
    static func from(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }
    
    
    func kt_drawRectWithRoundedCorner(_ radius: CGFloat, sizetoFit: CGSize, backgroundColor: UIColor, borderWidth: CGFloat, borderColor: UIColor) -> UIImage {
        
        let sizetoFit = sizetoFit
        let halfBorderWidth = CGFloat(borderWidth / 2.0)
        
        UIGraphicsBeginImageContextWithOptions(sizetoFit, false, UIScreen.main.scale)
        let context = UIGraphicsGetCurrentContext()
        
        context?.setLineWidth(borderWidth)
        context?.setStrokeColor(borderColor.cgColor)
        context?.setFillColor(backgroundColor.cgColor)
        
        let width = sizetoFit.width
        let height = sizetoFit.height
        
        context?.move(to: CGPoint(x: width - halfBorderWidth, y: radius + halfBorderWidth))
        context?.addArc(tangent1End: CGPoint(x: width - halfBorderWidth, y: height - halfBorderWidth), tangent2End: CGPoint(x: width - radius - halfBorderWidth, y: height - halfBorderWidth), radius: radius)
        context?.addArc(tangent1End: CGPoint(x: halfBorderWidth, y: height - halfBorderWidth), tangent2End: CGPoint(x: halfBorderWidth, y: height - radius - halfBorderWidth), radius: radius)
        context?.addArc(tangent1End: CGPoint(x: halfBorderWidth, y: halfBorderWidth), tangent2End: CGPoint(x: width - halfBorderWidth, y: halfBorderWidth), radius: radius)
        context?.addArc(tangent1End: CGPoint(x: width - halfBorderWidth, y: halfBorderWidth), tangent2End: CGPoint(x: width - halfBorderWidth, y: radius + halfBorderWidth), radius: radius)
        
        UIGraphicsGetCurrentContext()?.drawPath(using: .fillStroke)
        let output = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return output!
    }
    
    ///  画圆角
    var cutCircleImage: UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        
        let ctr = UIGraphicsGetCurrentContext() // 获取上下文
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) // 设置圆形
        ctr?.addEllipse(in: rect)
        
        ctr?.clip()  // 裁剪
        draw(in: rect) // 将图片画上去
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }

    
    // 加水印图片
    func imageAddWatermark(_ useImage: UIImage, transparentimg: UIImage) -> UIImage {
        
        let newSize = UIImage.scaleImage(useImage, imageLength: 600)
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let width = newSize.height >= newSize.width ? newSize.width : newSize.height
        transparentimg.draw(in: CGRect(x: newSize.width / 2 - width / 2, y: newSize.height / 2 -  width / 2, width: width, height: width), blendMode: CGBlendMode.normal, alpha: 1.0)
        let watermarkImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return watermarkImage!
    }
    
    
    // 加水印图片 2
    func addImgWatermark(_ transparentimg: UIImage, rect: CGRect,color: UIColor) -> UIImage {
        
        UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
        self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
        color.set()
        transparentimg.draw(in: rect, blendMode: CGBlendMode.normal, alpha: 1.0)
        let watermarkImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return watermarkImage!
    }
    
    
    
    
    //水印位置枚举
    enum WaterMarkCorner{
        case TopLeft
        case TopRight
        case BottomLeft
        case BottomRight
    }
    
    //添加图片水印方法
    func waterMarkedImage(waterMarkImage:UIImage, corner:WaterMarkCorner = .BottomRight,
                          margin:CGPoint = CGPoint(x: 20, y: 20), alpha:CGFloat = 1) -> UIImage{
        
        var markFrame = CGRect(x:0, y: 0, width:waterMarkImage.size.width,
                               height: waterMarkImage.size.height)
        let imageSize = self.size
        
        switch corner{
        case .TopLeft:
            markFrame.origin = margin
        case .TopRight:
            markFrame.origin = CGPoint(x: imageSize.width - waterMarkImage.size.width - margin.x,
                                       y: margin.y)
        case .BottomLeft:
            markFrame.origin = CGPoint(x: margin.x,
                                       y: imageSize.height - waterMarkImage.size.height - margin.y)
        case .BottomRight:
            markFrame.origin = CGPoint(x: imageSize.width - waterMarkImage.size.width - margin.x,
                                       y: imageSize.height - waterMarkImage.size.height - margin.y)
        }
        
        // 开始给图片添加图片
        UIGraphicsBeginImageContext(imageSize)
        self.draw(in: CGRect(x: 0, y:0, width: imageSize.width, height: imageSize.height))
        waterMarkImage.draw(in: markFrame, blendMode: .normal, alpha: alpha)
        let waterMarkedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return waterMarkedImage!
    }
    // 斜的 全图片水印  中心，一条
    static func getWaterMark_center(_ originalImage: UIImage?, title: String) -> UIImage? {
       
        //原始image的宽高
        guard let viewWidth = originalImage?.size.width, let viewHeight = originalImage?.size.height else { return nil }
        //为了防止图片失真，绘制区域宽高和原始图片宽高一样
        UIGraphicsBeginImageContext(CGSize(width: viewWidth, height: viewHeight))
        //先将原始image绘制上
        originalImage?.draw(in: CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight))
        //sqrtLength：原始image的对角线length。在水印旋转矩阵中只要矩阵的宽高是原始image的对角线长度，无论旋转多少度都不会有空白。
        let sqrtLength = sqrt(viewWidth * viewWidth + viewHeight * viewHeight)
        
        var fontx:UIFont = UIFont.systemFont(ofSize: 70)
        if title.count > 12 && title.count <= 16 {
             fontx = UIFont.systemFont(ofSize: 60)
        } else if title.count > 16 && title.count <= 20 {
             fontx = UIFont.systemFont(ofSize: 55)
        } else if title.count > 20 {
            fontx = UIFont.systemFont(ofSize: 45)
        }
        
         
        let attrStr = NSAttributedString(string: title, attributes: [NSAttributedString.Key.foregroundColor : UIColor.red, NSAttributedString.Key.font: fontx, NSAttributedString.Key.strokeWidth:2,NSAttributedString.Key.strokeColor:UIColor.red])
        //绘制文字的宽高
        let strWidth = attrStr.size().width
        let strHeight = attrStr.size().height
        
        //开始旋转上下文矩阵，绘制水印文字
        let context = UIGraphicsGetCurrentContext()
        
        //将绘制原点（0，0）调整到源image的中心
        context?.concatenate(CGAffineTransform(translationX: viewWidth / 2, y: viewHeight / 2))
        //以绘制原点为中心旋转
        context?.concatenate(CGAffineTransform(rotationAngle: CGFloat(-Double.pi / 2 / 2)))
        //将绘制原点恢复初始值，保证当前context中心和源image的中心处在一个点(当前context已经旋转，所以绘制出的任何layer都是倾斜的)
        
        let lm  = sqrt(viewWidth * viewWidth + viewWidth * viewWidth)

        let leftM = (lm - strWidth)/2
        
        context?.concatenate(CGAffineTransform(translationX: -lm / 2 + leftM, y: 0))
        
        title.draw(in: CGRect(x: 0, y: 0, width: strWidth, height: strHeight), withAttributes: [NSAttributedString.Key.foregroundColor : UIColor.red, NSAttributedString.Key.font: fontx, NSAttributedString.Key.strokeWidth:2,NSAttributedString.Key.strokeColor:UIColor.red])
        
        
        //根据上下文制作成图片
        let finalImg: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return finalImg
    }
    
    // 斜的 全图片水印
    static func getWaterMark(_ originalImage: UIImage?, title: String, andMark markFont: UIFont, andMark markColor: UIColor,V_space:CGFloat = 800) -> UIImage? {
        let HORIZONTAL_SPACE: CGFloat = 300
        var VERTICAL_SPACE = V_space
        
        //原始image的宽高
        guard let viewWidth = originalImage?.size.width, let viewHeight = originalImage?.size.height else { return nil }
        //为了防止图片失真，绘制区域宽高和原始图片宽高一样
        UIGraphicsBeginImageContext(CGSize(width: viewWidth, height: viewHeight))
        //先将原始image绘制上
        originalImage?.draw(in: CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight))
        //sqrtLength：原始image的对角线length。在水印旋转矩阵中只要矩阵的宽高是原始image的对角线长度，无论旋转多少度都不会有空白。
        let sqrtLength = sqrt(viewWidth * viewWidth + viewHeight * viewHeight)
        let attrStr = NSAttributedString(string: title, attributes: [NSAttributedString.Key.foregroundColor : markColor, NSAttributedString.Key.font: markFont])
        //绘制文字的宽高
        let strWidth = attrStr.size().width
        let strHeight = attrStr.size().height
        
        //开始旋转上下文矩阵，绘制水印文字
        let context = UIGraphicsGetCurrentContext()
        
        //将绘制原点（0，0）调整到源image的中心
        context?.concatenate(CGAffineTransform(translationX: viewWidth / 2, y: viewHeight / 2))
        //以绘制原点为中心旋转
        context?.concatenate(CGAffineTransform(rotationAngle: CGFloat(M_PI_2 / 3)))
        //将绘制原点恢复初始值，保证当前context中心和源image的中心处在一个点(当前context已经旋转，所以绘制出的任何layer都是倾斜的)
        context?.concatenate(CGAffineTransform(translationX: -viewWidth / 2, y: -viewHeight / 2))
        
        //计算需要绘制的列数和行数
        let horCount: Int = Int(sqrtLength / CGFloat(strWidth + HORIZONTAL_SPACE)) + 1
        let verCount: Int = Int(sqrtLength / CGFloat(strHeight + VERTICAL_SPACE)) + 1
        //此处计算出需要绘制水印文字的起始点，由于水印区域要大于图片区域所以起点在原有基础上移
        let orignX: CGFloat = -(sqrtLength - viewWidth) / 2
        let orignY: CGFloat = -(sqrtLength - viewHeight) / 2
        //在每列绘制时X坐标叠加
        var tempOrignX: CGFloat = orignX
        //在每行绘制时Y坐标叠加
        var tempOrignY: CGFloat = orignY
        for i in 0..<horCount * verCount {
            title.draw(in: CGRect(x: tempOrignX, y: tempOrignY, width: strWidth, height: strHeight), withAttributes: [NSAttributedString.Key.foregroundColor : markColor, NSAttributedString.Key.font: markFont])
            if i % horCount == 0 && i != 0 {
                tempOrignX = orignX
                tempOrignY += strHeight + VERTICAL_SPACE
            } else {
                tempOrignX += strWidth + HORIZONTAL_SPACE
            }
        }
        //根据上下文制作成图片
        let finalImg: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return finalImg
    }
    
    
    
    
    
    // 加时间水印图片
    func imageAddTimeWatermark(_ useImage: UIImage, transparentimg: UIImage) -> UIImage? {
        
        let newSize = useImage.size
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        transparentimg.draw(in: CGRect(x: 100, y: 50, width: newSize.width - 100, height: 100), blendMode: CGBlendMode.normal, alpha: 1.0)
        let watermarkImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return watermarkImage
    }
    
    ///对指定图片进行拉伸
    func resizableImage(_ name: String) -> UIImage {
        
        var normal = UIImage(named: name)!
        let imageWidth = normal.size.width * 0.5
        let imageHeight = normal.size.height * 0.5
        normal = self.resizableImage(withCapInsets: UIEdgeInsets(top: imageHeight, left: imageWidth, bottom: imageHeight, right: imageWidth))
        
        return normal
    }
    
    /**
     *  压缩上传图片到指定字节
     *
     *  image     压缩的图片
     *  maxLength 压缩后最大字节大小
     *
     *  return 压缩后图片的二进制
     */
    func compressImage(_ maxLength: Int) -> Data? {
        
        let newSize = UIImage.scaleImage(self, imageLength: 600)
        let newImage = UIImage.resizeImage(self, newSize: newSize)
        
        var compress: CGFloat = 0.9
        var data = newImage.jpegData(compressionQuality: compress)
        
        while (data?.count)! > maxLength && compress > 0.01 {
            compress -= 0.05
            data = newImage.jpegData(compressionQuality: compress)
        }
        
        return data
    }
    
    /**
     *  通过指定图片最长边，获得等比例的图片size
     *
     *  image       原始图片
     *  imageLength 图片允许的最长宽度（高度）
     *
     *  return 获得等比例的size
     */
   static func scaleImage(_ image: UIImage, imageLength: CGFloat) -> CGSize {
        
        var newWidth: CGFloat = 0.0
        var newHeight: CGFloat = 0.0
        let width = image.size.width
        let height = image.size.height
        
        if width > imageLength || height > imageLength {
            
            if width > height {
                
                newWidth = imageLength
                newHeight = newWidth * height / width
                
            } else if height > width {
                
                newHeight = imageLength
                newWidth = newHeight * width / height
                
            } else {
                
                newWidth = imageLength
                newHeight = imageLength
            }
            
        } else {
            
            newWidth = imageLength
            newHeight = imageLength
        }
        return CGSize(width: newWidth, height: newHeight)
    }
    
    /**
     *  获得指定size的图片
     *
     *  image   原始图片
     *  newSize 指定的size
     *
     *  return 调整后的图片
     */
    static func resizeImage(_ image: UIImage, newSize: CGSize) -> UIImage {
        UIGraphicsBeginImageContext(newSize)
        image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage!
    }
    
    // × 图
    var imageOfCross: UIImage {
        UIGraphicsBeginImageContextWithOptions(CGSize(width: 15, height: 15), false, 0)
        drawCross()
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    // 画 ×
    func drawCross() {
        // Cross Shape Drawing
        let crossShapePath = UIBezierPath()
        crossShapePath.move(to: CGPoint(x: 0, y: 15))
        crossShapePath.addLine(to: CGPoint(x: 15, y: 0))
        crossShapePath.move(to: CGPoint(x: 0, y: 0))
        crossShapePath.addLine(to: CGPoint(x: 15, y: 15))
        crossShapePath.lineCapStyle = CGLineCap.square
        crossShapePath.lineJoinStyle = CGLineJoin.round
        UIColor.white.setStroke()
        crossShapePath.lineWidth = 1
        crossShapePath.stroke()
    }
    
 
    // V 图
        static func imageOfV() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(CGSize(width: 20, height: 20), false, 0)
       drawV()
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    
    
    // 画 V
        static func drawV() {
        // Cross Shape Drawing
        let crossShapePath = UIBezierPath()
        crossShapePath.move(to: CGPoint(x: 0, y: 0))
        crossShapePath.addLine(to: CGPoint(x: 10, y: 20))
        crossShapePath.addLine(to: CGPoint(x: 20, y: 0))
        crossShapePath.lineCapStyle = CGLineCap.square
        crossShapePath.lineJoinStyle = CGLineJoin.round
        #colorLiteral(red: 0.3019607843, green: 0.3019607843, blue: 0.3019607843, alpha: 1).setStroke()
        crossShapePath.lineWidth = 1
        crossShapePath.stroke()
    }
    
    
    // < 图
    var imageOfBack: UIImage {
        UIGraphicsBeginImageContextWithOptions(CGSize(width: 20, height: 20), false, 0)
        drawBack()
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    
    
    // 画 <
    func drawBack() {
        // Cross Shape Drawing
        let crossShapePath = UIBezierPath()
        crossShapePath.move(to: CGPoint(x: 10, y: 0))
        crossShapePath.addLine(to: CGPoint(x: 0, y: 10))
        crossShapePath.addLine(to: CGPoint(x: 10, y: 20))
        crossShapePath.lineCapStyle = CGLineCap.square
        crossShapePath.lineJoinStyle = CGLineJoin.round
        #colorLiteral(red: 0.3019607843, green: 0.3019607843, blue: 0.3019607843, alpha: 1).setStroke()
        crossShapePath.lineWidth = 1
        crossShapePath.stroke()
    }
    
    static func drawPin(color:UIColor) -> UIImage {
        
        
        let rect = CGRect(x: 0.0, y: 0.0, width: 30, height: 60)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        // 画圆
        context!.addEllipse(in: CGRect(x:0,y:0,width:30,height:30))
        color.set()
        // 渲染
        context!.fillPath()
        
        
        // 直线
        context!.move(to: CGPoint(x: 15, y: 30))
        context!.addLine(to: CGPoint(x: 15, y: 60))
        
        context!.setLineWidth(3.0)
        context!.setLineCap(.round)
        context!.setLineJoin(.round)
        context!.strokePath()
        
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
        
        
    }
    
    
    
    // > 图
    var imageOfForward: UIImage {
        UIGraphicsBeginImageContextWithOptions(CGSize(width: 20, height: 20), false, 0)
        drawForward()
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    // 画 >
    func drawForward() {
        // Cross Shape Drawing
        let crossShapePath = UIBezierPath()
        crossShapePath.move(to: CGPoint(x: 0, y: 0))
        crossShapePath.addLine(to: CGPoint(x: 10, y: 10))
        crossShapePath.addLine(to: CGPoint(x: 0, y: 20))
        crossShapePath.lineCapStyle = CGLineCap.square
        crossShapePath.lineJoinStyle = CGLineJoin.round
        #colorLiteral(red: 0.3019607843, green: 0.3019607843, blue: 0.3019607843, alpha: 1).setStroke()
        crossShapePath.lineWidth = 1
        crossShapePath.stroke()
    }
    
    // |=> 图
    static func imageOfPointRight(color:UIColor,width:CGFloat = 1) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(CGSize(width: 80, height: 40), false, 0)
        drawPointRight(color: color,width:width)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    // 画 |=>
    static  func drawPointRight(color:UIColor,width:CGFloat = 1) {
        // Cross Shape Drawing
        let crossShapePath = UIBezierPath()
        crossShapePath.move(to: CGPoint(x: 0, y: 0))
        crossShapePath.addLine(to: CGPoint(x: 70, y: 0))
        crossShapePath.addLine(to: CGPoint(x: 80, y: 20))
        crossShapePath.addLine(to: CGPoint(x: 70, y: 40))
        crossShapePath.addLine(to: CGPoint(x: 0, y: 40))
        crossShapePath.addLine(to: CGPoint(x: 0, y: 0))
         crossShapePath.lineCapStyle = CGLineCap.square
        crossShapePath.lineJoinStyle = CGLineJoin.round
        color.setStroke()
        crossShapePath.lineWidth = width
        crossShapePath.stroke()
    }
    
}
extension UIImage {
    func isEqualToImage(_ image: UIImage) -> Bool {
        return self.pngData() == image.pngData()
    }
}
enum waterMarkPosition {
    case topLeft,topRight,bottomLeft,bottomRight
}

struct waterMarkStringType {
    var text:String
    var textColor:UIColor
    var position:waterMarkPosition
}

// MARK:  水印图片
extension UIImage {
    /// 图片加水印
  
    func drawTextInImage(waterStrings: [waterMarkStringType]) -> UIImage {
        
        
        // 开启和原图一样大小的上下文（保证图片不模糊的方法）
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        
        // 图形重绘
        self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
        
        var fontX:UIFont?
        if self.size.width < 1000 {
            fontX = .systemFont(ofSize: 37)
        } else if self.size.width < 2000 {
            fontX = .systemFont(ofSize: 80)
        } else if self.size.width < 3000 {
            fontX = .systemFont(ofSize: 100)
        } else if self.size.width < 4000 {
            fontX = .systemFont(ofSize: 135)
        } else if self.size.width < 5000 {
            fontX = .systemFont(ofSize: 170)
        } else {
            fontX = .systemFont(ofSize: 210)
        }
        
        for item in waterStrings {
            // 手动计算换行
            var sep = item.text.components(separatedBy: "\n")
            for i in 0..<sep.count {
                if sep[i].count > 20 {
                    let pre = sep[i].prefix(20)
                    let suf = sep[i].suffix( sep[i].count - 20)
                    sep[i] = pre + "\n" + suf
                }
             }
           let finalStr = sep.joined(separator: "\n")
         
            let suffixAttr: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor:item.textColor, NSAttributedString.Key.font:fontX!]
            let attrS = NSMutableAttributedString(string: finalStr, attributes: suffixAttr)
             // 文字属性
            let size =  attrS.size()
            
            // 绘制文字
            switch item.position {
            case .topLeft:
                attrS.draw(in: CGRect(x:self.size.width/20,y:self.size.height/20,width: size.width,height:size.height))
            case .topRight:
                attrS.draw(in: CGRect(x:self.size.width/2,y:self.size.height/20,width: size.width,height:size.height))
            case .bottomLeft:
                attrS.draw(in: CGRect(x:5,y:self.size.height - 50 - size.height,width: self.size.width - 5,height:size.height))
            case .bottomRight:
                attrS.draw(in: CGRect(x:self.size.width/2,y:self.size.height/20 * 18,width: size.width,height:size.height))
                
            }
            
        }
        
        
        
        
        
        // 从当前上下文获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        
        return image!
    }
    func showM() {
        guard var data = self.jpegData(compressionQuality: 1) else {
            return
        }
        print("图大小kb: \( Double((data.count)/1024))")
    }
    
    
}

